﻿using DotNetCore.CAP;
using Microsoft.Extensions.Configuration;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.EmailHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using NP.BPMReportPlatform.Entities.BPM_Process;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.RecurringJobs
{
    /// <summary>
    /// 给需要提交排课的人员发送邮件
    /// </summary>
    public class PKPTRecurringJob : BpmReportPlatformRecurringJob, IPKPTRecurringJob
    {
        private readonly SqlSugarClient _db, _dbPlatform, _dbProcess;
        private readonly IEmailAPPService _emailAPPService;
        private readonly ICapPublisher _capBus;
        private readonly IConfiguration _configuration;
        private readonly ILogger _logger;
        public PKPTRecurringJob(ISqlSugarAppService sqlSugarAppService, IEmailAPPService emailAPPService,
            ICapPublisher capBus,
            IConfiguration configuration, ILogger logger)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _dbProcess = sqlSugarAppService.GetProcessInstance();
            _configuration = configuration;
            _emailAPPService = emailAPPService;
            _capBus = capBus;
            _logger = logger;
        }

        /// <summary>
        /// 每月17号12点，排课平台邮件催发提醒
        /// </summary>
        /// <returns></returns>
        public async Task SendEmailToPKUserNotice()
        {
            try
            {
                // 发送邮件
                // 从通知配置表中获取人员
                var tasks = _db.Queryable<SendMailService>()
                   .Where(x => x.ProcessCode == "PKXZTJDS" && x.IsDelete == 0).Select(x => x.UserId).Distinct().ToList();

                var users = await _dbPlatform.Queryable<Users>().Where(x => tasks.Contains(x.WorkNumber)).ToListAsync();
                if (!users.Any())
                {
                    _logger.Error("SendEmailToPKUserNotice，用户数据未找到");
                }
                // 流程查看地址
                string processUrl = await GetPCStartUrl();
                // 发送提醒邮件
                users.ForEach(x =>
                {
                    // 发送提醒邮件
                    _ = SendMail1(x.Email, processUrl, "");
                });
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="email"></param>
        /// <param name="startInstanceLink"></param>
        /// <param name="ccEmails"></param>
        /// <returns></returns>
        private async Task SendMail1(string email, string startInstanceLink, string ccEmails = "")
        {
            var topic = "您好，每月20日需提交3个月的滚动预估排班，请您及时在排课平台中完成。";
            var content = "";
            var templateName = "PKPT1.cshtml";
            if (!string.IsNullOrEmpty(templateName))
            {
                content = _emailAPPService.GenerateEmailTemplate(templateName);
                content = !string.IsNullOrEmpty(startInstanceLink) ?
                    content.Replace("{StartInstanceLink}", startInstanceLink) : string.Empty;
            }
            if (!string.IsNullOrEmpty(content) && !string.IsNullOrEmpty(email))
            {
                await _capBus.PublishAsync("bpmnew.EmailAppService.SendEmailAsync",
                  new Dto.SendEmailSimpleDto()
                  {
                      To = email,
                      Subject = topic,
                      Body = content,
                      CC = ccEmails
                  });
            }
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="email"></param>
        /// <param name="startInstanceLink"></param>
        /// <param name="ccEmails"></param>
        /// <returns></returns>
        private async Task SendMail2(string email, string startInstanceLink, string ccEmails = "")
        {
            var topic = "您好，每月20日需提交3个月的滚动预估排班，若还没完成/更新，请您抓紧时间哦！";
            var content = "";
            var templateName = "PKPT2.cshtml";
            if (!string.IsNullOrEmpty(templateName))
            {
                content = _emailAPPService.GenerateEmailTemplate(templateName);
                content = !string.IsNullOrEmpty(startInstanceLink) ?
                    content.Replace("{StartInstanceLink}", startInstanceLink) : string.Empty;
            }
            if (!string.IsNullOrEmpty(content) && !string.IsNullOrEmpty(email))
            {
                await _capBus.PublishAsync("bpmnew.EmailAppService.SendEmailAsync",
                  new Dto.SendEmailSimpleDto()
                  {
                      To = email,
                      Subject = topic,
                      Body = content,
                      CC = ccEmails
                  });
            }
        }

        /// <summary>
        /// 获取流程发起页面url
        /// </summary>
        /// <returns></returns>
        private async Task<string> GetPCStartUrl()
        {
            var process = await _dbProcess.Queryable<Processes>().FirstAsync(x => x.BTID.Equals("PKXZTJ") && x.InUse == 1);
            if (process == null)
            {
                return "";
            }

            return string.Format(_configuration["BPM:PCStartUrl"], process.ProcessId);
        }

        /// <summary>
        /// 每月19号12点，排课平台邮件催发有变更及时更新提醒
        /// </summary>
        /// <returns></returns>
        public async Task SendEmailToPKUserUdNotice()
        {
            try
            {
                // 发送邮件
                // 从通知配置表中获取人员
                var tasks = _db.Queryable<SendMailService>()
                   .Where(x => x.ProcessCode == "PKXZTJDS" && x.IsDelete == 0).Select(x => x.UserId).Distinct().ToList();

                var users = await _dbPlatform.Queryable<Users>().Where(x => tasks.Contains(x.WorkNumber)).ToListAsync();
                if (!users.Any())
                {
                    _logger.Error("SendEmailToPKUserUdNotice，用户数据未找到");
                }
                // 流程查看地址
                string processUrl = await GetPCStartUrl();
                // 发送提醒邮件
                users.ForEach(x =>
                {
                    // 发送提醒邮件
                    SendMail2(x.Email, processUrl, "");
                });
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
